import React, { useMemo, useCallback } from 'react'
import { Radio } from 'antd'
import { RadioChangeEvent } from 'antd/lib/radio'
import { parse } from './../../utils/json/json'

interface FieldNames {
  label: string;
  value: string
}

interface IProps {
  value?: any;
  id?: string;
  onChange?(value: string, id?: string): void;
  dataSource?: any[] | string;
  fieldNames?: FieldNames;
  disabled?: boolean
}

const defaultFieldNames = { label: 'label', value: 'value' }

export default ({ id, onChange, dataSource, fieldNames, value, disabled }: IProps) => {

  const handleDataSource = useMemo(() => {
    if (!dataSource) return [];
    if (Array.isArray(dataSource)) return dataSource;
    return parse(dataSource) || [];
  }, [dataSource])

  const handleFieldNames = useMemo(() => fieldNames || defaultFieldNames, [fieldNames])

  const _onChange = useCallback((e: RadioChangeEvent) => {
    onChange?.(e.target.value, id);
  }, [id, onChange])

  return (
    <Radio.Group value={value} onChange={_onChange} disabled={disabled}>
      {handleDataSource.map((item: any) => (
        <Radio value={item[handleFieldNames.value]}>
          {item[handleFieldNames.label]}
        </Radio>
      ))}
    </Radio.Group>
  )
}